package com.example.transform;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 *
 *  * @projectName myflinkstu
 *  * @title     Test8_CustomPartition
 *  * @package    com.example.transform
 *  * @description
 *  * @author hjx
 *  * @date   2022-3-22 9:52
 *  * @version V1.0.0
 *  * @copyright 2022 ty
 *
 */
public class Test8_CustomPartition {

    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 将自然数按照奇偶分区
        env.fromElements(1, 2, 3, 4, 5, 6, 7, 8)
                .partitionCustom(new Partitioner<Integer>() {
                    @Override
                    public int partition(Integer key, int numPartitions) {
                        return key % 2;
                    }
                }, new KeySelector<Integer, Integer>() {
                    @Override
                    public Integer getKey(Integer value) throws Exception {
                        return value;
                    }
                })
                .print().setParallelism(2);

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
